package cn.itsource.pethome.department.service.impl;

import cn.itsource.pethome.base.service.impl.BaseServiceImpl;
import cn.itsource.pethome.department.domain.Department;
import cn.itsource.pethome.department.mapper.DepartmentMapper;
import cn.itsource.pethome.department.query.DepartmentQuery;
import cn.itsource.pethome.department.service.IDepartmentService;
import cn.itsource.pethome.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;



    @Override
    public Long count(DepartmentQuery departmentQuery) {
        return departmentMapper.count(departmentQuery);
    }

    @Override
    public void insert(Department department) {
        System.out.println(department);
        //判断department.parent_id是否有值
        if (department.getParent_id() == null) {
            //为null则为最高部门
            department.setDirPath("/"+department.getId());
        }else {
            //存在上级部门，父级部门的id通过id查询dirpath进行拼接成为自己的dirpath
            Long parent_id = department.getParent_id();
            //查询父级的信息
            Department department1 = departmentMapper.queryOne(parent_id);
            //拼接dirpath
            department.setDirPath(department1.getDirPath()+"/"+department.getId());
        }
        departmentMapper.insert(department);
    }





    @Override
    public void deleteAll(List<Long> ids) {
        departmentMapper.deleteAll(ids);
    }

    @Override
    public List<Department> deptTree() {
        //1.查询全部部门
        //2.找到顶级部门
        List<Department> departments = departmentMapper.queryAll();
        List<Department> firstCourseType = new ArrayList<>();
        for (Department department : departments) {
            //判断是不是顶级
            if(department.getParent_id() == null){
                firstCourseType.add(department);
            }else{
                //3.不是顶级的找自己的爹把自己放进去
                for (Department department2 : departments) {
                    if(department.getParent_id() == department2.getId()){
                        department2.getChildren().add(department);
                    }
                }
            }
        }
        return firstCourseType;
    }
}
